﻿using System;
using Stock.Core.MongoDB;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Stock.Model;

namespace Stock.Core.Common
{
     
    public class MongoLoggerService:ILoggerService
    {
        IOptions<MongoOptions> _opt;
        IMongoBaseRepository<LogModel> _mongo;
        public MongoLoggerService(IOptions<MongoOptions> opt, IMongoBaseRepository<LogModel> m)
        {
            _opt = opt;
            _mongo = m;
        }

        public void Debug(LogModel content, string filePrefixName = null, string path = null)
        {
            content.LogType = "Debug";
            _mongo.Create(content);
        }

		public void Error(LogModel content, string filePrefixName = null, string path = null)
        {
            content.LogType = "Error";
			_mongo.Create(content);
        }

		public void Log(LogModel content, string LogType, string filePrefixName = null, string path = null)
		{
			content.LogType = LogType;
			_mongo.Create(content);
		}

        public async Task RemoveAll()
        {
            await _mongo.RemoveAll();
        }


        public dynamic GetLog(DateTime? day, int? executedTime = null, string LogType = "Error")
        {
            var qq = from l in _mongo.GetQueryable()
                         //where l.ExecuteStartTime > day

                     select l;
            if (executedTime != null)
                qq = qq.Where(aa => aa.ExecutedTime > executedTime);
            if (LogType != null)
                qq = qq.Where(aa => aa.LogType == LogType);
            if (day != null)
                qq = qq.Where(aa => aa.ExecuteStartTime > day.Value.AddHours(8));
            var data = qq.OrderByDescending(q => q.ExecuteStartTime).Take(100).ToList();
            return new BaseResult() { Data = data, DataCount = qq.Count(), IsSuccess = true };
        }
    }
}
